package com.changan.alm2.version.common.config;

import cn.hutool.core.util.StrUtil;
import com.changan.alm2.version.common.bean.resp.CommonResult;
import com.changan.alm2.version.common.bean.resp.Responsive;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Map;

/**
 * springmvc统一返回处理器
 *
 * @Author yaodong
 * @Date 2022/10/14 4:22 PM
 * @Version 1.0
 */
@RestControllerAdvice
public class ReturnValueHandler implements ResponseBodyAdvice<Object> {
    /**
     * supports方法要返回为true才会执行beforeBodyWrite方法
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        // 如果返回值类型是ResponseEntity或者Responsive, 直接返回false就好了
        boolean support = !returnType.getParameterType().equals(ResponseEntity.class)
                && !returnType.getParameterType().equals(Responsive.class)
                && !returnType.getParameterType().equals(CommonResult.class);
        return support;
//        return true;
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
       /* boolean support = !returnType.getParameterType().equals(ResponseEntity.class)
                && !returnType.getParameterType().equals(Responsive.class)
                && !returnType.getParameterType().equals(CommonResult.class);
        if (!support) {
            return data;
        }*/

        if (data instanceof Map) {
            Integer success = (Integer) ((Map<?, ?>) data).get("status");
            if (success != null) {
                return data;
            }
        }
        // String类型不能直接包装，需要特别处理, 请思考为什么
        if (returnType.getParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在JsonResponse里返回
                return objectMapper.writeValueAsString(CommonResult.success(data));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("返回String类型错误");
            }
        }
        if (StrUtil.equals(returnType.getParameterType().getName(), "void") && mediaType.equals(MediaType.APPLICATION_JSON)) {
            return CommonResult.success();
        }
        return CommonResult.success(data);
    }
}